//
//  NSPieceView.m
//  SpeedTest
//
//  Created by Han Mingjie on 2020/1/6.
//  Copyright © 2020 MingJie Han. All rights reserved.
//

#import "NSPieceView.h"
#define MAXIMUM_Leads_IN_VIEW 12

@interface NSPieceView(){
    BOOL isClean;
    NSMutableArray *lead_status_array;
    NSMutableArray *headViewArray;
    CGMutablePathRef ecg_lines[MAXIMUM_Leads_IN_VIEW];
    NSMutableArray *leadsConnectArray;
}

@end

@implementation NSPieceView
@synthesize dataSource;
@synthesize index;
@synthesize data_index;
@synthesize ecg_name;
@synthesize ecg_lead_status;
@synthesize line_color;
@synthesize lost_line_color;
@synthesize line_width;
@synthesize x_start_init_value;
@synthesize x_seek_per_point;
@synthesize isDrawNewLine;

-(id)initWithFrame:(CGRect)frameRect{
    self = [super initWithFrame:frameRect];
    if (self){
        ecg_name = @[@"I"];
        lead_status_array = [[NSMutableArray alloc] init];
#if TARGET_OS_IOS
        self.backgroundColor = [UIColor clearColor];
#endif
        line_color = [UIColor greenColor];
        line_width = 1.6f;
        x_start_init_value = -1.f;
        x_seek_per_point = 0.2f;
        isClean = YES;
        isDrawNewLine = YES;
        
        headViewArray = [[NSMutableArray alloc] init];
        
        for (int i=0;i<MAXIMUM_Leads_IN_VIEW;i++){
            ecg_lines[i] = nil;
        }
    }
    return self;
}

-(void)clean_in_thread{
    isClean = YES;
#if TARGET_OS_IOS
    dispatch_async(dispatch_get_main_queue(), ^{
        //尾影
        [UIView animateWithDuration:0.25 animations:^{
            self.alpha = 0.f;
        }];
    });
#endif
}

-(void)fresh_in_thread{
    isClean = NO;
    self->isDrawNewLine = YES;
    dispatch_async(dispatch_get_main_queue(), ^{
        self.alpha = 1.f;
        [self setNeedsDisplay];
    });
}

-(void)setFrame:(CGRect)frame{
    [super setFrame:frame];
    isClean = YES;
}
    
#if !TARGET_OS_IOS
-(void)setFrameSize:(NSSize)newSize{
    [super setFrameSize:newSize];
    isClean = YES;
}

-(void)setBoundsSize:(NSSize)newSize{
    [super setBoundsSize:newSize];
    isClean = YES;
}
#endif

-(void)dealloc{
    for (int i=0;i<MAXIMUM_Leads_IN_VIEW;i++){
        CGMutablePathRef path = ecg_lines[i];
        if (path){
            CGPathRelease(path);
            ecg_lines[i] = nil;
        }
    }
}

-(void)reBuildLines{
    NSArray <NSArray <NSNumber *>*>*ecg_values_array = [dataSource getValueFrom:self];
    if (nil == ecg_values_array || 0 == ecg_values_array.count){
        return;
    }
    if (nil == leadsConnectArray){
        leadsConnectArray = [[NSMutableArray alloc] init];
    }else{
        [leadsConnectArray removeAllObjects];
    }
    for (int i=0;i<MAXIMUM_Leads_IN_VIEW;i++){
        CGMutablePathRef path = ecg_lines[i];
        if (path){
            CGPathRelease(path);
            ecg_lines[i] = nil;
        }
    }
    while (headViewArray.count < ecg_values_array.count) {
        UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0.f, 0.f, line_width * 6.f, line_width * 6.f)];
        headView.layer.masksToBounds = YES;
        headView.layer.cornerRadius = headView.frame.size.width/2.f;
#if TARGET_OS_IOS
        headView.backgroundColor = [UIColor colorWithRed:0.17 green:0.81 blue:0.8 alpha:1.f];
        headView.alpha = 0.f;
#endif
        [self addSubview:headView];
        [headViewArray addObject:headView];
    }
    
    for (int i=0;i<ecg_values_array.count;i++){
        NSArray <NSNumber *>* ecg_values = [ecg_values_array objectAtIndex:i];
        BOOL lead_connected = YES;
        if (ecg_lead_status){
            lead_connected = [[ecg_lead_status objectAtIndex:i] boolValue];
            [leadsConnectArray addObject:[NSNumber numberWithBool:lead_connected]];
        }
        
        CGMutablePathRef ecg_line_path = CGPathCreateMutable();
        float x_value = x_start_init_value;
        BOOL isPenDown = NO;
        float y_center = 0;
        float x_center = 0;
        for (NSNumber *num in ecg_values){
            float y_value = [num floatValue];
            //修复I导 超出显示区域时，丢失一部分的错误
//            if (y_value <= 0){
//                break;
//            }
            if (isPenDown){
                CGPathAddLineToPoint(ecg_line_path, NULL, x_value, y_value);
            }else{
                CGPathMoveToPoint(ecg_line_path, NULL, x_value, y_value);
                isPenDown = YES;
            }
            x_value += x_seek_per_point;
            if (0 == y_center && x_value >= self.frame.size.width){
                y_center = y_value;
                x_center = x_value;
            }
        }
        CGPathMoveToPoint(ecg_line_path, NULL, -1.f, -1.f);
        CGPathCloseSubpath(ecg_line_path);
        ecg_lines[i] = ecg_line_path;
        
#if TARGET_OS_IOS
        if (isDrawNewLine){
            UIView *headView = [headViewArray objectAtIndex:i];
            headView.alpha = 1.f;
            headView.transform = CGAffineTransformMakeScale(1.f, 1.f);
            [headView setCenter:CGPointMake(x_center, y_center)];
            [UIView animateWithDuration:0.04 animations:^{
                headView.transform = CGAffineTransformMakeScale(0.5f, 0.5f);
            } completion:^(BOOL finished) {
                headView.alpha = 0.f;
            }];
        }
#endif
    }
    ecg_values_array = nil;
}

-(void)drawRect:(CGRect)dirtyRect{
    [super drawRect:dirtyRect];
    if (isClean){
        return;
    }
    
//    NSLog(@"draw piece.");
    if (isDrawNewLine){
        //读取数据重新画线并带尾影
        [self reBuildLines];
    }
    
    for (int i=0;i<leadsConnectArray.count;i++){
        CGMutablePathRef ecg_line_path = ecg_lines[i];
        BOOL lead_connected = [[leadsConnectArray objectAtIndex:i] boolValue];
#if TARGET_OS_IOS
        CGContextRef currentContext = UIGraphicsGetCurrentContext();
#else
        CGContextRef currentContext = [NSGraphicsContext currentContext].CGContext;
#endif
        CGContextSetLineWidth(currentContext, line_width);
        if (lead_connected){
            CGContextSetStrokeColorWithColor(currentContext, line_color.CGColor);
        }else{
            CGContextSetStrokeColorWithColor(currentContext, lost_line_color.CGColor);
        }
        CGContextSetLineCap(currentContext, kCGLineCapRound);
        CGContextSetLineJoin(currentContext, kCGLineJoinRound);
        CGContextBeginPath(currentContext);
        CGContextAddPath(currentContext, ecg_line_path);
        CGContextStrokePath(currentContext);
    }
    
    isDrawNewLine = NO;
    return;
}

@end
